'use strict';

const path = require('path');
// css压缩
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
// html压缩
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    index: './src/index.ts',
    // search: './src/search.js'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name]_[chunkhash:8].js'
  },
  // 生产环境
  mode: 'production',
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    // 配置别名
    alias: {
      // 将@指向src目录
      '@': path.resolve(__dirname, 'src/')
    }
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /.css$/,
        use: [
          MiniCssExtractPlugin.loader, // 压缩css
          'css-loader'
        ]
      },
      {
        test: /.scss$/,
        use: [
          MiniCssExtractPlugin.loader, // 替换style-loader
          'css-loader',	// 解析css
          'sass-loader' // 解析less
        ]
      },
      {
        test: /.(png|jpg|gif|jpeg)$/, // 解析图片
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[name]_[hash:8].[ext]' // 8位hash
            }
          }
        ]
      },
      {
        test: /.(woff|woff2|eot|ttf|otf)$/, // 解析字体
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[name]_[hash:8][ext]' // 8位hash
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({ // 压缩css
      filename: '[name]_[contenthash:8].css' // 8位hash
    }),
    new OptimizeCSSAssetsPlugin({
      assetNameRegExp: /\.css$/g,
      cssProcessor: require('cssnano')
    }),
    new HtmlWebpackPlugin({ // 压缩html
      template: path.join(__dirname, 'src/index.html'),
      filename: 'index.html',
      chunks: ['index'],
      inject: true,
      minify: {
        html5: true,
        collapseWhitespace: true,
        preserveLineBreaks: false,
        minifyCSS: true,
        minifyJS: true,
        removeComments: false // 保留注释
      }
    }),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'src/search.html'),
      filename: 'search.html',
      chunks: ['search'],
      inject: true,
      minify: {
        html5: true,
        collapseWhitespace: true,
        preserveLineBreaks: false,
        minifyCSS: true,
        minifyJS: true,
        removeComments: false
      }
    })
  ]
};
